package com.tantan.server;

import com.tantan.model.UserMessage;

import java.io.IOException;

/**
 * 编程实现服务器的主功能
 */
public class ServerView {

    /**
     * 使用合成复用原则
     */
    private ServerInitClose sic;
    private ServerDao sd;

    /**
     * 通过构造方法实现成员变量的初始化
     * @param sic
     */
    public ServerView(ServerInitClose sic , ServerDao sd) {
        this.sic = sic;
        this.sd = sd;
    }

    /**
     * 自定义成员方法实现客户端发来信息的接收和处理
     */
    public void serverReceive() throws IOException, ClassNotFoundException {
        UserMessage tum = (UserMessage) sic.getOis().readObject();
        System.out.println("接收到的消息是" + tum);
        if("managerCheck".equals(tum.getType())){
            if(sd.serverManagerCheck(tum.getUser())){
                tum.setType("success");
            }else{
                tum.setType("fail");
            }
        }
        if("userCheck".equals(tum.getType())){
            if(sd.serverStudentCheck(tum.getUser())){
                tum.setType("success");
            }else{
                tum.setType("fail");
            }
        }
        if("increaseStudents".equals(tum.getType())){
            if(sd.increaseStudents(tum.getUser())){
                tum.setType("success");
            }else{
                tum.setType("fail");
            }
        }
        if("deleteStudents".equals(tum.getType())){
            if(sd.deleteStudents(tum.getUser())){
                tum.setType("success");
            }else{
                tum.setType("fail");
            }
        }
        if("changeStudents".equals(tum.getType())){
            if(sd.changeStudents(tum.getUser())){
                tum.setType("success");
            }else{
                tum.setType("fail");
            }
        }
        if("findStudents".equals(tum.getType())){
            if(sd.findStudents(tum.getUser())){
                tum.setType("success");
            }else{
                tum.setType("fail");
            }
        }
        //将校验结果发送给客户端
        sic.getOos().writeObject(tum);
        System.out.println("服务器发送校验结果成功！");
    }
}
